package org.hyl.javabase.model;

import java.util.Enumeration;
import java.util.Vector;

//�۲���ģʽ
public class ObserverDemo {
	public static void main(String[] args) {
		Subject sub = new MySubject();
		sub.add(new Observer1());
		sub.add(new Observer2());

		sub.operation();
	}

}

class Observer1 implements IObserver {

	public void update() {
		System.out.println("observer1 has received!");
	}
}

class Observer2 implements IObserver {

	public void update() {
		System.out.println("observer2 has received!");
	}

}

interface Subject {

	/* ���ӹ۲��� */
	public void add(IObserver observer);

	/* ɾ���۲��� */
	public void del(IObserver observer);

	/* ֪ͨ���еĹ۲��� */
	public void notifyObservers();

	/* ����Ĳ��� */
	public void operation();
}

abstract class AbstractSubject implements Subject {

	private Vector<IObserver> vector = new Vector<IObserver>();

	public void add(IObserver observer) {
		vector.add(observer);
	}

	public void del(IObserver observer) {
		vector.remove(observer);
	}

	public void notifyObservers() {
		Enumeration<IObserver> enumo = vector.elements();
		while (enumo.hasMoreElements()) {
			enumo.nextElement().update();
		}
	}
}

class MySubject extends AbstractSubject {

	public void operation() {
		System.out.println("update self!");
		notifyObservers();
	}

}
